#include "renderablegameworld.h"
#include "resourcemanager.h"
#include <sstream>

RenderableGameWorld::RenderableGameWorld() :
	GameWorld(false, NULL)
{
}

RenderableGameWorld::~RenderableGameWorld()
{
	//dtor
}


void RenderableGameWorld::DrawObjects(sf::RenderWindow& app)
{
	ResourceManager& rm = ResourceManager::GetInstance();
	for (GameObjectMapIT it = planets.begin(); it != planets.end(); ++it)
	{
		GameObject& obj = *(it->second);
		rm.sprPlanet.SetPosition(obj.pos.x, obj.pos.y);
		rm.sprPlanet.SetRotation(obj.angle * 180 / M_PI);
		float scale = obj.size / 186.f /*size of planet image in pixels*/;
		rm.sprPlanet.SetScale(scale, scale);
		app.Draw(rm.sprPlanet);
	}

	for (GameObjectListIT it = bullets.begin(); it != bullets.end(); ++it)
	{
		GameObject& obj = **it;
		rm.sprBullet.SetPosition(obj.pos.x, obj.pos.y);
		rm.sprBullet.SetRotation(obj.angle * 180 / M_PI);
		app.Draw(rm.sprBullet);
	}

	// Weapons
	for (GameObjectMapIT it = weapons.begin(); it != weapons.end(); ++it)
	{
		GameObject& weapon = *(it->second);
		if (weapon.parent == 0)
		{
			rm.sprWeapon.SetPosition(weapon.pos.x, weapon.pos.y);
			rm.sprWeapon.SetRotation(weapon.angle * 180 / M_PI);
			app.Draw(rm.sprWeapon);
		}
		else
		{
			GameObject* ship = GetObject(weapon.parent);
			if (ship)
			{
				sf::Vector2f pos(ship->pos.x, ship->pos.y);
				pos.x += weapon.pos.x * cosf(ship->angle) + weapon.pos.y * sinf(ship->angle);
				pos.y += -weapon.pos.x * sinf(ship->angle) + weapon.pos.y * cosf(ship->angle);
				rm.sprWeapon.SetPosition(pos.x, pos.y);
				rm.sprWeapon.SetRotation((weapon.angle + ship->angle) * 180 / M_PI);
				app.Draw(rm.sprWeapon);
			}
		}
	}

	for (GameObjectMapIT it = ships.begin(); it != ships.end(); ++it)
	{
		GameObject& obj = *(it->second);
		if (obj.lifespan >= 0.0f)
		{
			rm.sprShip.SetPosition(obj.pos.x, obj.pos.y);
			rm.sprShip.SetRotation(obj.angle * 180 / M_PI);
			if (obj.lifespan < 2.0f)
			{
				if (((int)(obj.lifespan * 10)) % 5 > 2)
				{
					rm.sprShip.SetColor(sf::Color(255,255,255, 140));
				}
				else
				{
					rm.sprShip.SetColor(sf::Color(255,255,255,255));
				}
			}
			else
			{
				rm.sprShip.SetColor(sf::Color(255,255,255,255));
			}
			app.Draw(rm.sprShip);
		}
	}

	for (GameObjectMapIT it = ships.begin(); it != ships.end(); ++it)
	{
		GameObject& obj = *(it->second);
		std::stringstream stream;
		stream << "ship " << (int)obj.id;
		//sf::String label(stream.str(), rm.fontSmall, FONT_SMALL_SIZE);
		//label.SetPosition(obj.pos.x, obj.pos.y - 20);
		//app.Draw(label);
	}
}
